import FormRequest from "@bis/requests/form";
import QuestionRequest from "@bis/requests/question";
import QuestionType from "@bis/types/question";
import QuestionResponse from "@bis/interface/question";
import AnswerRequest from "@bis/requests/answer";
import { FieldType } from "./constants";
import { deepClone } from "@bis/utils/objectFun";
import dayjs from "dayjs";

// 处理问题的转换
export const dealQue = (params) => {
  const { question, formStore, type = "toWeb", answers } = params;
  const isRender = !formStore.isDesigner;
  const answer =
    (answers &&
      answers.find((ans) => ans.questionId === question.id)?.answer) ||
    "";
  const _val = deepClone(question);
  _val.type = FieldType[_val.type];
  if (type === "toBack") {
    delete _val.disabled;
  } else {
    _val.disabled = true;
    if (isRender) {
      _val.answer = answer;
      _val.disabled = !!answer;
    }
    switch (_val.type) {
      case "input":
        delete _val.optionItems;
        break;
      case "radio":
        delete _val.unit;
        break;
      case "checkbox":
        // _val.answer = answer.split("|");
        // console.log(_val.answer, "checkbox", answer, _val);
        delete _val.unit;
        break;
      case "select":
        delete _val.unit;
        break;
      case "date":
      case "table":
        const cols = _val.cols;
        cols.forEach((col) => {
          if (col.hasOwnProperty("disabled")) {
            col.disabled = isRender ? !!answer : true;
          }
        });
        if (!formStore.isDesigner) {
          cols.pop();
        }
        break;
      default:
        break;
    }
  }
  return _val;
};

// 添加问题
export const addQue = async (question, formStore) => {
  const id = formStore.formConfig.id;
  const _que = dealQue({ question, formStore, type: "toBack" });
  const res: QuestionResponse = await QuestionRequest.addQuestion({
    ..._que,
    platformId: 1,
    formId: id,
  });
  if (res.code === 200) {
    return {
      status: true,
      data: { ...question, id: res.data.id },
    };
  } else {
    return {
      status: false,
      message: res.message,
    };
  }
};

// 更改保存问题
export const editQue = async (question, formStore) => {
  const id = formStore.formConfig.id;
  // 判断是不是子组件
  const isChildren = !!question.containerId;
  let _question = question;
  if (isChildren) {
    _question = formStore.questions.find(
      (que) => que.id === question.containerId
    );
    _question[question.colIdx] = question;
  }
  const _que = dealQue({ question: _question, formStore, type: "toBack" });
  const res: QuestionResponse = await QuestionRequest.editQuestion({
    ..._que,
    platformId: 1,
    formId: id,
  });
  if (res.code === 200) {
    return {
      status: true,
      data: { ...question, id: res.data.id },
    };
  } else {
    return {
      status: false,
      message: res.message,
    };
  }
};

// 更改排序
export const queSequence = async (formStore) => {
  const list = formStore.questions.map((que) => {
    return que.id;
  });
  const id = formStore.formConfig.id;
  const res = await FormRequest.editForm({
    sequenceList: list,
    platformId: 1,
    id,
  });
};

// 处理答案
export const dealAnswer = (answers, type = "toWeb") => {
  answers.map((answer) => {
    switch (answer.type) {
      case "input":
      case "radio":
      case "checkbox":
      case "select":
        break;
      case "date":
        answer.answer = answer.answer
          ? dayjs(answer.answer).format("YYYY-MM-DD")
          : null;

        break;
      case "table":
        let ans = "";
        let _answer = answer.answer;
        _answer.forEach((item, index) => {
          let str = "";
          str = item.join("$$");
          if (index !== _answer.length - 1) {
            ans += str + "__";
          } else {
            ans += str;
          }
        });
        answer.answer = ans;
        break;
      default:
        break;
    }
    return answer;
  });
  return answers;
};

// 获取答案
export const getAnswers = async (params) => {
  const res = await AnswerRequest.getAnswers(params);
  return res.data ? res.data.answers : [];
};

// 提交答案
export const submitAnswer = async (formStore) => {
  let answers = formStore.questions.map((que: QuestionType) => {
    return {
      questionId: que.id,
      type: que.type,
      answer: que.answer,
    };
  });
  answers = dealAnswer(answers, "toBack");
  console.log(answers, "submitAnswer");
  // 请求接口保存答案
  const res = await AnswerRequest.addAnswers({
    platformId: 1,
    formId: formStore.formConfig.id,
    userId: 1,
    answers,
  });
  // if(res.)
};
